package com.cennavi.minemap.conf;

import java.sql.SQLException;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = { "classpath:application.properties" })
public class MineMapDataSourceConfiguration {


    @Value("${spring.minemap.pg.driverClassName}")
    private String driverClassName;
    
    @Value("${spring.minemap.pg.host}")
    private String host;
    
    @Value("${spring.minemap.pg.port}")
    private String port;
    
    @Value("${spring.minemap.pg.database}")
    private String database;
    
    @Value("${spring.minemap.pg.username}")
    private String username;
    
    @Value("${spring.minemap.pg.password}")
    private String password;
    
    @Value("${spring.minemap.pg.max-active}")
    private int maxActive;
    
    @Value("${spring.minemap.pg.max-idle}")
    private int maxIdle;
    
    @Value("${spring.minemap.pg.max-wait}")
    private int maxWait;
    
    @Value("${spring.minemap.pg.initial-size}")
    private int initialSize;
    
    @Value("${spring.minemap.pg.validation-query}")
    private String validationQuery;
    
    @Value("${spring.minemap.pg.test-on-borrow}")
    private boolean testOnBorrow;
    
    @Value("${spring.minemap.pg.test-while-idle}")
    private boolean testWhileIdle;
    
    @Value("${spring.minemap.pg.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;
	
	@Bean(name="pgDataSource")  
	@Primary
    public DataSource primaryDataSource() throws SQLException {  
        System.out.println("-------------------- spring.minemap.pg init ---------------------");  
        
        DataSource dataSource = new DataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl("jdbc:postgresql://" + host + ":" + port + "/" + database);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxIdle(maxIdle);
        dataSource.setMaxWait(maxWait);
        dataSource.setInitialSize(initialSize);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        dataSource.setMinEvictableIdleTimeMillis(5000);
        return dataSource;
    }  
}
